package com.blb.community.Config;

import com.blb.community.Utils.JwtUtils;
import com.blb.community.Utils.RsaUtils;
import com.blb.community.pojo.ResponseResult;
import com.blb.community.pojo.ZyOwner;
import com.blb.community.service.ZyOwnerService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Configuration
public class successHandlerConfig implements AuthenticationSuccessHandler {

    @Resource
    private ZyOwnerService zyOwnerService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ResponseResult.write(ResponseResult.ok(JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey,JwtUtils.EXPIRE_MINUTES)),httpServletResponse);
        String s="登录成功";
        ResponseResult.write(ResponseResult.ok(s),httpServletResponse);
//        获得登录后的用户名
//        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        if(user == null){
//            throw new RuntimeException("用户为空");
//        }
//        //生成accessToken
//        String accessToken = JwtUtils.generateToken(user.getUsername(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
//        //截取一部分，生成refreshToken
//        String uid = accessToken.substring(0,10);
//        String refreshToken = JwtUtils.generateToken(uid, RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES * 2);
//        HashMap<String,String> tokens = new HashMap<>();
//        tokens.put("accessToken",accessToken);
//        tokens.put("refreshToken",refreshToken);
//        //将两个token发送给前端
//        //让自定义响应头可见
//        httpServletResponse.setHeader("Access-Control-Expose-Headers","tokens");
//        //把两个token放到响应头和响应数据一起返回
//        httpServletResponse.setHeader("tokens",new ObjectMapper().writeValueAsString(tokens));
//        ResponseResult.write(ResponseResult.ok(tokens),httpServletResponse);
    }
}
